<?php 
/**********************************INCLUDE*********************************** *
* **************************************************************************** */
include_once '../app/App.php';
include_once '../account/Account.php';
include_once '../db/DatabaseManager.php';
include_once '../returndata/LoginReturnData.php';

/**
 * @author nicholas malacarne <nicholas.malacarne@gmail.com>, kayvan sarikhani <ksarikhani@gmail.com>
 * 
 * This script is used to log an account into the app.
 */

// required get data fields -nm
$required = array( 'email', 'password' );

// return data for this script -nm
$returnData = new LoginReturnData();

try {
    
    // check if we have required parameters -nm
    if ( ! App::paramOK( $required, $_GET ) ){
        
        throw new ErrorException( "Error Processing Parameters !" );
    }
    
    // get instance of App -nm
    $app = App::init();
    
    // connect to database -nm
    $db = new DatabaseManager( 'db.refinedguitar.com', 'troop410', 'GTCtr00p410!', 'troop410' );
    
    // strip post data -nm
    $email      = filter_input( INPUT_GET, 'email'  );
    $password   = filter_input( INPUT_GET, 'password' );
        
    // extract account data by email -nm
    $accountData = $db->getRowByValue( "accounts", "email", $email );

    // if account exists and passwords match -nm
    if ( isset( $accountData ) && $accountData[ "password" ] == $password ){
        
        // log account into app -nm
        $app->setAccount( new Account( $accountData ) );
        
        // add account data -nm
        $returnData->addData( LoginReturnData::KEY_ACCOUNT , $app->getInfo() );

    }else{

        // no account data found/passwords do not match -nm
        $returnData->addData( LoginReturnData::KEY_INVALID_DATA , "Invalid Username/Password");
    }
    
}catch( Exception $e ){
    
    // get the file/line/message of the exception -nm
    $eData = array( "file" => $e->getFile(), 
                    "line" => $e->getLine(), 
                    "msg" => $e->getMessage() );
    
    // add exception data -nm
    $returnData->addData( LoginReturnData::KEY_EXCEPTION, $eData );
    
} // TODO: handle specific exceptions -nm

// return data in json format -nm
$returnData->returnJSON();
